package com.hs.shirodemo01.config;

import com.hs.shirodemo01.mapper.TbUserMapper;
import com.hs.shirodemo01.pojo.TbPermission;
import com.hs.shirodemo01.pojo.TbRole;
import com.hs.shirodemo01.pojo.TbUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName UserRealm
 * @Description  自定义的Realm
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    TbUserMapper mapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        TbUser user = (TbUser) principalCollection.getPrimaryPrincipal();
        List<TbRole> roles = mapper.selectAllRoles(user.getId());
        List<TbPermission> permissions = mapper.selectAllPermission(user.getId());
        Set<String> roleSet = roles.stream().map(TbRole::getRoleName).collect(Collectors.toSet());
        Set<String> permissionSet = permissions.stream().map(TbPermission::getCode).collect(Collectors.toSet());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleSet);
        authorizationInfo.setStringPermissions(permissionSet);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        TbUser user = mapper.selectByUsername(principal);
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
    }
}
